/*
 * @Author: song
 * @Description:编辑器模式下 进行动画的播放
 * @Date: 2024年04月21日 星期日 16:04:42
 * @Modify:
 */

using System;
using UnityEngine;

namespace SCore.UI
{
    [ExecuteInEditMode]
    public class SAnimationEditorPose : MonoBehaviour
    {
        public Animator Animator;
        public AnimationClip Clip;

        [Range(0, 1)] public Single Time;

        void Update()
        {
            if (Application.isPlaying)
            {
                Destroy(this);
                return;
            }

#if UNITY_EDITOR
            if (Clip)
            {
                // try to grab animator
                if (!Animator)
                {
                    Animator = gameObject.GetComponentInParent<Animator>();

                    if (!Animator)
                    {
                        Animator = gameObject.GetComponentInChildren<Animator>();

                        if (!Animator)
                        {
                            return;
                        }
                    }
                }

                Time = Mathf.Clamp01(Time);
                Clip.SampleAnimation(Animator.gameObject, Clip.length * Time);
            }
#endif
        }
    }
}
#if UNITY_EDITOR
namespace SCore.UI
{
    using UnityEditor;
    using UnityEditor.Animations;

    [CustomEditor(typeof(SAnimationEditorPose))]
    public class SAnimationEditorPoseEditor : Editor
    {
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            // grab poser component
            var poser = target as SAnimationEditorPose;
            if (!poser)
            {
                return;
            }

            // try to grab animator
            var animator = poser.gameObject.GetComponentInParent<Animator>();

            if (!animator)
            {
                animator = poser.gameObject.GetComponentInChildren<Animator>();

                if (!animator)
                {
                    return;
                }
            }

            // grab animator controller
            var ac = (AnimatorController)animator.runtimeAnimatorController;


            foreach (var layer in ac.layers)
            {
                foreach (var state in layer.stateMachine.states)
                {
                    var clip = state.state.motion as AnimationClip;
                    if (clip)
                    {
                        if (GUILayout.Button(state.state.name))
                        {
                            poser.Clip = clip;
                        }
                    }
                }
            }
        }
    }
}
#endif